package com.gdzn.netty.redis.queue;


import cn.hutool.json.JSONUtil;
import com.gdzn.common.core.utils.DateUtils;
import com.gdzn.common.core.utils.JsonUtil;
import com.gdzn.netty.domain.DeviceCallParam;
import com.gdzn.netty.service.IDeviceRedisService;
import com.gdzn.netty.service.IDeviceService;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class MessageReceiver {

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private IDeviceRedisService deviceRedisService;
    /**
     * 接收消息方法
     */
    public void receiverMessage(String message) {
        System.out.println("收到一条调用新消息：" + message);
        Map<String,Object> deviceCallParam = JSONUtil.toBean(message,Map.class);
        log.info("******redis pub message callDevice**推送命令操作设备,deviceCallParam:{}", deviceCallParam);
        String devId = (String) deviceCallParam.get("devId");
        ChannelHandlerContext ctx = deviceRedisService.getChannelByDevId(devId);
        if (null != ctx) {
//            deviceCallParam.setTxnNo(System.currentTimeMillis());
            deviceCallParam.put("txnNo",System.currentTimeMillis());
            sendByChannel(JSONUtil.toJsonStr(deviceCallParam), ctx);
        }else{
            log.info("******redis pub message  callDevice**获取不到channel***,设备id:{}",devId);
        }
    }

    /**
     * 通过管道->推送消息到客户端
     * @param resp
     * @param ctx
     */
    private void sendByChannel(String resp, ChannelHandlerContext ctx){
        log.info("***redis pub message sendByChannel***时间：{}, 开始发送给客户端：{}", DateUtils.getTime(), JsonUtil.toJSON(resp));
        String channelId = ctx.channel().id().asLongText();
        //String resp = JSONUtil.toJsonStr(deviceCallParam);
        ctx.channel().writeAndFlush(resp);
        log.info("*** redis pub message  sendByChannel***返回给管道channelId:{},客户端", channelId);
    }
}
